"""
职位数据库管理
提供职位描述的管理和检索功能
"""

import json
import os
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime

logger = logging.getLogger(__name__)

class JobDatabase:
    """职位数据库管理类"""
    
    def __init__(self, data_file: str = "knowledge_base/jobs.json"):
        """
        初始化职位数据库
        
        Args:
            data_file: 职位数据文件路径
        """
        self.data_file = data_file
        self.jobs = []
        
        # 确保目录存在
        os.makedirs(os.path.dirname(data_file), exist_ok=True)
        
        # 加载数据
        self._load_data()
        
        # 如果没有数据，初始化默认职位
        if not self.jobs:
            self._init_default_jobs()
    
    def _load_data(self):
        """加载职位数据"""
        try:
            if os.path.exists(self.data_file):
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    self.jobs = json.load(f)
                logger.info(f"加载了 {len(self.jobs)} 个职位")
            else:
                self.jobs = []
                logger.info("职位数据文件不存在，将创建新文件")
        except Exception as e:
            logger.error(f"加载职位数据失败: {str(e)}")
            self.jobs = []
    
    def _save_data(self):
        """保存职位数据"""
        try:
            with open(self.data_file, 'w', encoding='utf-8') as f:
                json.dump(self.jobs, f, ensure_ascii=False, indent=2)
            logger.info("职位数据保存成功")
        except Exception as e:
            logger.error(f"保存职位数据失败: {str(e)}")
            raise
    
    def _init_default_jobs(self):
        """初始化默认职位数据"""
        default_jobs = [
            {
                "id": "job_001",
                "title": "前端开发工程师",
                "company": "某互联网公司",
                "description": "负责公司产品的前端开发工作，使用Vue.js、React等现代前端框架。",
                "skills": ["Vue.js", "React", "JavaScript", "HTML", "CSS"],
                "salary_range": "15k-25k",
                "location": "北京",
                "category": "前端开发"
            },
            {
                "id": "job_002",
                "title": "后端开发工程师",
                "company": "某科技公司",
                "description": "负责公司产品的后端开发工作，使用Python、Java等语言。",
                "skills": ["Python", "Java", "MySQL", "Redis", "Spring Boot"],
                "salary_range": "20k-35k",
                "location": "上海",
                "category": "后端开发"
            }
        ]
        self.jobs = default_jobs
        self._save_data()
    
    def add_job(self, job_data: Dict[str, Any]) -> str:
        """
        添加新职位
        
        Args:
            job_data: 职位数据
            
        Returns:
            职位ID
        """
        # 生成唯一ID
        job_id = f"job_{len(self.jobs) + 1:03d}"
        job_data["id"] = job_id
        self.jobs.append(job_data)
        self._save_data()
        
        logger.info(f"添加职位成功: {job_id}")
        return job_id
    
    def get_job(self, job_id: str) -> Optional[Dict[str, Any]]:
        """
        获取职位信息
        
        Args:
            job_id: 职位ID
            
        Returns:
            职位信息
        """
        for job in self.jobs:
            if job["id"] == job_id:
                return job
        return None
    
    def get_all_jobs(self) -> List[Dict[str, Any]]:
        """
        获取所有职位
        
        Returns:
            职位列表
        """
        return self.jobs
    
    def search_jobs(self, query: str) -> List[Dict[str, Any]]:
        """
        搜索职位
        
        Args:
            query: 搜索关键词
            
        Returns:
            匹配的职位列表
        """
        results = []
        query_lower = query.lower()
        
        for job in self.jobs:
            # 检查关键词匹配
            if (query_lower in job["title"].lower() or
                query_lower in job["description"].lower()):
                results.append(job)
        
        return results
    
    def update_job(self, job_id: str, job_data: Dict[str, Any]) -> bool:
        """
        更新职位信息
        
        Args:
            job_id: 职位ID
            job_data: 更新的职位数据
            
        Returns:
            是否更新成功
        """
        for i, job in enumerate(self.jobs):
            if job["id"] == job_id:
                job_data["id"] = job_id
                self.jobs[i] = job_data
                self._save_data()
                logger.info(f"更新职位成功: {job_id}")
                return True
        
        return False
    
    def delete_job(self, job_id: str) -> bool:
        """
        删除职位
        
        Args:
            job_id: 职位ID
            
        Returns:
            是否删除成功
        """
        for i, job in enumerate(self.jobs):
            if job["id"] == job_id:
                del self.jobs[i]
                self._save_data()
                logger.info(f"删除职位成功: {job_id}")
                return True
        
        return False
    
    def get_job_categories(self) -> List[str]:
        """
        获取所有职位类别
        
        Returns:
            职位类别列表
        """
        categories = set()
        for job in self.jobs:
            if "category" in job:
                categories.add(job["category"])
        return list(categories)
    
    def get_jobs_by_category(self, category: str) -> List[Dict[str, Any]]:
        """
        根据类别获取职位
        
        Args:
            category: 职位类别
            
        Returns:
            职位列表
        """
        return [job for job in self.jobs if job.get("category") == category] 